import cv2
import math

import numpy as np

points = []


def mouse_points(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDOWN:
        size = len(points)
        if size != 0 and size % 3 != 0:
            cv2.line(img,
                     tuple(points[round((size - 1) / 3) * 3]), (x, y), (0, 255, 0), 2)
        cv2.circle(img, (x, y), 5, (0, 255, 0), cv2.FILLED)
        points.append((x, y))


def gradient(pt1, pt2):
    return (pt2[1] - pt1[1]) / (pt2[0] - pt1[0])


def calc_angle():
    pt1, pt2, pt3 = points[0], points[1], points[2]
    m1 = gradient(pt1, pt2)
    m2 = gradient(pt1, pt3)
    angleR = math.atan((m2 - m1) / (1 + (m2 * m1)))
    angleO = round(math.degrees(angleR))
    cv2.putText(img, str(abs(angleO)), (pt1[0] - 40, pt1[1] - 20), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)


img = cv2.imread('images/angles.png')
while True:
    cv2.imshow('Image', img)
    cv2.setMouseCallback('Image', mouse_points)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        points = []
        img = cv2.imread('images/angles.png')
    elif cv2.waitKey(1) & 0xFF == 27:
        break

    if len(points) % 3 == 0 and len(points) > 0:
        calc_angle()

cv2.destroyAllWindows()
